package com.mlamp.链表;

public class 两数相加 {

    public static void main(String[] args) {
        LNode head1 = new LNode(2);
        head1.next = new LNode(4);
        head1.next.next = new LNode(3);
        head1.next.next.next = new LNode(2);

        LNode head2 = new LNode(5);
        head2.next = new LNode(6);
        head2.next.next = new LNode(6);
        LNode lNode = addTwoNumbers(head1, head2);
        LNode tmp = lNode;
        print(tmp);
    }

    private static void print(LNode head) {
        while (head != null) {
            System.out.print(head.value + " ");
            head = head.next;
        }
    }


    //(2 -> 4 -> 3 -> 2) + (5 -> 6 -> 6)
    public static LNode addTwoNumbers(LNode l1, LNode l2) {
        LNode p1 = l1, p2 = l2;
        int cur = 0;
        LNode result = new LNode(-1);
        LNode head = result;
        while (p1 != null && p2 != null) {
            int tmp = p1.value + p2.value + cur;
            cur = tmp / 10;
            tmp = tmp % 10;
            head.next = new LNode(tmp);
            head = head.next;
            p1 = p1.next;
            p2 = p2.next;
        }
        while (p1 != null) {
            int tmp = p1.value + cur;
            cur = tmp / 10;
            tmp = tmp % 10;
            head.next = new LNode(tmp);
            head = head.next;
            p1 = p1.next;
        }

        while (p2 != null) {
            int tmp = p2.value + cur;
            cur = tmp / 10;
            tmp = tmp % 10;
            head.next = new LNode(tmp);
            head = head.next;
            p2 = p2.next;
        }

        return result.next;

    }

}
